package com.shujia.flink.core

import java.util.Properties

import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.runtime.state.StateBackend
import org.apache.flink.runtime.state.filesystem.FsStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer

object Demo7ExactlyOnce {
  def main(args: Array[String]): Unit = {

    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(20000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    //当任务取消的时候是否保留checkpoint,默认不保留
    env.getCheckpointConfig.enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)
    /**
      * 指定保存状态的位置
      *
      */
    //文件系统的状态后端，可以说hdfs
    val stateBackend: StateBackend = new FsStateBackend("hdfs://master:9000/data/flink/checkpoint")
    env.setStateBackend(stateBackend)






    val properties = new Properties()
    //kafka集群地址
    properties.setProperty("bootstrap.servers", "master:9092")
    //消费者组，随便写, 一条消息在一个组内只被消费一次
    properties.setProperty("group.id", "asdasd")

    //创建kafka消费者
    val consumer = new FlinkKafkaConsumer[String]("words", new SimpleStringSchema(), properties)

    //使用kafka source
    val linesDS: DataStream[String] = env.addSource(consumer)

    linesDS.flatMap(_.split(">"))
      .map((_, 1))
      .keyBy(_._1)
      .sum(1)
      .print()

    env.execute()


  }

}
